<?php

namespace App\Admin\Controllers;

use App\Models\ArticleModel;
use App\Models\CollectionArticle;
use App\Models\Support;
use App\Models\WorkModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Table;
use App\Models\BookModel;

use getID3;
use getid3_lib;
use Illuminate\Support\Arr;//laravel 数组处理
use Illuminate\Support\Str;//laravel 字符全处理
use Illuminate\Support\MessageBag;

use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Grid\Displayers\ContextMenuActions;
use Illuminate\Support\Facades\DB;



class ArticleController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '文章管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new ArticleModel());

        // 最原始的`按钮图标`形式
        $grid->setActionClass(Actions::class);

        $grid->filter(function($filter) {
            // 关联查询
            $filter->where(function ($query){
                $query -> whereHas('book',function ($query){
                    $query -> where('book_title','like',"%".$this -> input."%");
                });
            },'书本名称');
            // 在这里添加字段过滤器
            $filter->like('article_title', '文章标题');
        });

        $grid->model()->orderBy('order','asc');

        $grid->column('id', __('Id'))->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('article_title','文章标题')->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('order','排序')->editable()->style('display:table-cell;vertical-align:middle;text-align:center;');

        $bookModel = new BookModel();
        $grid->column('book_id', '所属书本')->display(function ($book_id)use ($bookModel){
            return $bookModel->where('id',$book_id)->value('book_title');
        })->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('book.book_logo', '书本封面')->image('', 80, 80)->style('display:table-cell;vertical-align:middle;text-align:center;');
       // $grid->column('article_cover', '背景图')->image('', 180, 180);
        $grid->column('created_at', '创建时间')->style('display:table-cell;vertical-align:middle;text-align:center;');
        $grid->column('updated_at', '更新时间')->style('display:table-cell;vertical-align:middle;text-align:center;');

        // 默认为每页20条
        $grid->paginate(10);
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(ArticleModel::findOrFail($id));

        $show->field('id','文章ID');
        $show->field('article_title','文章标题');
        $show->field('article_content','文章内容');

        $show->book('所属书本', function ($book) {
            $book->setResource('/admin/book-models');
            $book->id('书本ID');
            $book->book_title('书籍名称');
            $book->book_logo('书籍封面')->image();
            $book->author('作者');
            $book->article_number('章节数');
            $book->created_at('创建时间');
        });

        $show->class_work_info('对应作业',function ($class_work_info){
            $class_work_info->setResource('/admin/work-models');

            $class_work_info->disableCreateButton();
            $class_work_info->disablePagination();
            $class_work_info->disableFilter();
            $class_work_info->disableExport();
            $class_work_info->disableRowSelector();
            $class_work_info->disableColumnSelector();
            $class_work_info->disableActions();

            $class_work_info->id('作业ID')->style('width:200px;text-align:center');
            $class_work_info->title('标题')->width(200);
            $class_work_info->describe('任务描述')->width(200);
            $class_work_info->type('提交作业类型')->using([1 => '文字', 2 => '音频'])->width(200);
        });

        $show->field('book_id','所属书本');
        //$show->field('article_cover', '封面图')->image();
        $show->field('created_at', '创建时间');
        $show->field('updated_at', '更新时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new ArticleModel());

        $form->hidden('id','id');
        $form->text('article_title','文章标题')->attribute(['data-title' => 'title...'])->required();;

        //
        if(!empty(request()->route()->parameters())){
            //dd(request()->route()->parameters());
            $article_id = request()->route()->parameters()['article_model'];
            if(!empty($article_id)){
                $articleObj  = ArticleModel::where('id',$article_id)->first();
                //dd($articleObj);
                $form->tools(function (Form\Tools $tools) use ($articleObj) {
                    //跳转到下一个
                    $next_article = ArticleModel::where('id','!=',$articleObj->id)
                        ->where('book_id', $articleObj->book_id)
                        ->where('order', '>', $articleObj->order)
                        ->orderBy('order', 'asc')
                        ->orderBy('id', 'asc')
                        ->first();

                    $top_article = ArticleModel::where('id','!=',$articleObj->id)
                        ->where('book_id', $articleObj->book_id)
                        ->where('order', '<', $articleObj->order)
                        ->orderBy('order', 'desc')
                        ->orderBy('id', 'desc')
                        ->first();

                    //如果有下一条则展示按钮
                    if ($next_article) {
                        $url = '/admin/article-models/'.$next_article->id.'/edit';
                        $tools->append("<a class='btn btn-sm btn-primary mallto-next' href='{$url}' target='_top'>下一条</a> &nbsp;");
                    }

                    //如果有上一条则展示按钮
                    if ($top_article) {
                        $url = '/admin/article-models/'.$top_article->id.'/edit';
                        $tools->append("<a class='btn btn-sm btn-primary mallto-next' href='{$url}' target='_top'>上一条</a> &nbsp;");
                    }

                    if(!empty($articleObj->book_id)){
                        $url2 = '/admin/book-models/'.$articleObj->book_id;
                        $tools->append("<a class='btn btn-sm btn-primary mallto-next' href='{$url2}' target='_top'>查看书本详情</a> &nbsp;");
                    }

                });
            }
        }

        //$form->editor('article_content','文章内容');
        $form->UEditor('article_content','文章內容')->options(['initialFrameHeight' => 200])->required();

        $form->divider();

        $form->number('order','排序(从小到大数字)')->required();
        $form->text('reader_link','领读者');
        $form->file('article_leader','上传录音')
            ->move('/upload/music/'.date('Y-m-d'))
            ->uniqueName();

        $form->select('chadui','插队排序')->options(
            [
                2=>'否',
                1=>'是',
            ]
        )->default(2)
            ->help('插队后该排序后面的序号将随之改变');

        //dd($_GET);
        $get = $_GET;
        if(empty($get['book_id'])){
            $form->select('book_id','书本')->options(function ($id){
                return BookModel::/*where('id',$id)->*/pluck('book_title','id');
            })->default(0);
        }elseif(!empty($get['book_id']) && $get['book_id']!=0){
            $form->hidden('book_id')->value($get['book_id']);
        }

/*        $form->image('article_cover', '背景图')
            ->move('/upload/images/'.date('Ymd'))
            ->uniqueName();*/

        $form->hidden('playtime','时长');

        $form->ignore(['chadui']);
        //保存前回调
        $form->saving(function (Form $form) {
            //dd($_POST,$_GET);
            $chadui = !empty($_POST['chadui'])?$_POST['chadui']:1;
            $book_id = $form->book_id;
            $order = $form->order;
            $id = $form->id;

            if($chadui == 1){

                $min_new_data = [];
                $max_new_data = [];
                $update_data = [];

                //原ID
                $old_order = ArticleModel::where('id',$id)->value('order');

                $query = ArticleModel::where('book_id',$book_id)
                        ->where('order','!=',0);
                        //->where('order','>=',$order);

                    if(!empty($id)){
                       $query->where('id','!=',$id);
                    }

                     $article =  $query->orderBy('order','ASC')
                        ->pluck('order','id')
                        ->toArray();
                    //dd($article,$id);

                    if(count($article)>0){
                        //$new_data =[];
                        //dd($old_order);
                        foreach ($article as $k=>$v) {
                            //dd($v > $old_order);
                           // dd($old_order!='null',$old_order);
                            if(!empty($old_order)){
                                if ($v > $old_order) {
                                    $max_new_data[] = [
                                        'id' => $k,
                                        'order' => $v,
                                    ];
                                }

                                if ($v >= $order && $v < $old_order) {
                                    $min_new_data[] = [
                                        'id' => $k,
                                        'order' => $v,
                                    ];
                                }
                            }else{

                                if($v == $order){
                                    continue;
                                }
                                if ($v > $order) {
                                    $max_new_data[] = [
                                        'id' => $k,
                                        'order' => $v,
                                    ];
                                }

                                if ($v < $order) {
                                    $min_new_data[] = [
                                        'id' => $k,
                                        'order' => $v,
                                    ];
                                }
                            }

                        }

                      //dd($max_new_data,$min_new_data,$old_order,$article);

                      if(count($max_new_data) > 0){
                          foreach ($max_new_data as $k=>$v){
                              $order += 1;
                              //dd($order);
                              $max_data[$k]['id'] = $v['id'];
                              $max_data[$k]['order'] = $order;
                          }
                          //dd($max_data);
                          $end = end($max_data);

                      }else{
                          $end = $order;
                      }


                      //dd($end);
                        $min_data = [];
                      if(count($min_new_data) > 0){
                          //  dd(222);
                          foreach ($min_new_data as $kk=>$vv){
                              $end['order'] += 1;
                              $min_data[$kk]['id'] = $vv['id'];
                              $min_data[$kk]['order'] = $end['order'];
                          }
                      }

                    }

                    //dd($min_data,$max_data);
                if(count($max_new_data)>0 || count($min_new_data)>0){
                   //dd($max_data,$min_data);
                    $update_data = $min_data;
                    if(count($max_data) > 0){
                        $update_data = array_merge($max_data,$min_data);
                    }

                   //dd($update_data,$max_data,$min_data);
                    ArticleModel::updateBatch('article',$update_data);
                }

            }
            //}
            //獲取时长 前端获取不到
            //dd($_FILES);
            if(!empty($_FILES['article_leader'])){
                if($_FILES['article_leader']['size']>0){
                    if(!empty($_FILES['article_leader'])){
                        $path = $_FILES['article_leader']['tmp_name'];
                        $mediaTool = new \getID3();
                        $mediaInfo = $mediaTool->analyze($path);

                        if(empty($mediaInfo['playtime_seconds'])){
                            $error = new MessageBag([
                                'title'   => '格式错误',
                                'message' => '目前支持MP3,AAC,M4A,AMR等格式',
                            ]);

                            return back()->with(compact('error'));
                        }
                        $form->playtime = $mediaInfo['playtime_seconds'];

                    }
                }
            }
        });

        $form->deleting(function (Form $form){

            //dd(request()->route()->parameters());
            if(!empty(request()->route()->parameters())){
                $article_id = request()->route()->parameters()['article_model'];
                //dd($article_id);
                CollectionArticle::where('article_id',$article_id)->delete();
                Support::where('article_id',$article_id)->delete();
            }

        });

        $form->saved(function (Form $form) use($get) {
            // "after-save" => "2"
            $post = $_POST;
            $id = $form->model()->id;

           if(empty($post['after-save'])){
             $url = '/admin/article-models/'.$id.'/edit';
               // 跳转页面
               return redirect($url);
            }
        });

        return $form;
    }
}
